//
//  SJSearchViewController.m
//  WSL
//
//  Created by CJ on 2017/10/23.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJSearchViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJSearchApi.h"
#import "SJSpaceStationAddApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>

#import "SJTreeViewController.h"
#import "SJTxtDetailViewController.h"
#import "SJFunctionBar.h"
#import "SJOtherFunctionBar.h"

@interface SJSearchViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate, SJFunctionBarDelegate, SJOtherFunctionBarDelegate>

@property (nonatomic, strong) UIView *navigationBarView; // 背景
@property (nonatomic, strong) UITextField *searchField;

////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;

@end

@implementation SJSearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)dealloc {
    SJLogFunc;
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 0;
    [self setupUI];
    [self.searchField becomeFirstResponder];
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"search_bt_cancel"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .bottomSpaceToView(_navigationBarView, SJLayoutFrame(0))
        .rightSpaceToView(_navigationBarView, SJMargin)
        .heightIs(SJLayoutFrame(39))
        .widthIs(SJLayoutFrame(60));
        
        UIView *searchBG = [UIView new];
        searchBG.backgroundColor = SJColorHexString(@"#ffffff");
        searchBG.alpha = .1;
        searchBG.sd_cornerRadius = @(SJCornerRadius);
        [_navigationBarView addSubview:searchBG];
        searchBG.sd_layout
        .centerYEqualToView(backButton)
        .heightIs(SJLayoutFrame(39))
        .leftSpaceToView(_navigationBarView, SJMargin)
        .rightSpaceToView(backButton, SJMargin);
        
        UIImageView *searchImg = [UIImageView new];
        searchImg.image = [UIImage imageNamed:@"search_icon_search"];
        [_navigationBarView addSubview:searchImg];
        searchImg.sd_layout
        .centerYEqualToView(searchBG)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(19))
        .heightIs(SJLayoutFrame(20))
        .widthIs(SJLayoutFrame(20));
        
        [_navigationBarView addSubview:self.searchField];
        self.searchField.sd_layout
        .centerYEqualToView(searchBG)
        .leftSpaceToView(searchImg, SJLayoutFrame(12))
        .rightEqualToView(searchBG)
        .heightIs(SJLayoutFrame(39));
    }
    
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITextField *)searchField{
    
    if (!_searchField) {
        
        _searchField = [UITextField new];
        _searchField.returnKeyType = UIReturnKeySearch;
        _searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchField.textColor = SJColorHexString(@"#ffffff");
        _searchField.font = [UIFont systemFontOfSize:SJLayoutFrame(14)];
        
        [_searchField addTarget:self action:@selector(editingChanged) forControlEvents:UIControlEventEditingChanged];
        [_searchField addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventEditingDidEndOnExit];
        
        NSString *holderText = @"输入搜索内容";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(14)]
                            range:NSMakeRange(0, holderText.length)];
        _searchField.attributedPlaceholder = placeholder;
        
    }
    return _searchField;
}

- (void)editingChanged {
    
}

- (void)searchAction {
    
    [self loadNewData];
    
}

- (UIView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIView new];
        _detailImageView.backgroundColor = SJColorHexString(@"#00000090");
        _detailImageView.alpha = 0;
        
        
        UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setImage:[UIImage imageNamed:@"detail_btn_more_nor"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
        
        //        [_detailImageView addSubview:moreButton];
        moreButton.sd_layout
        .centerYEqualToView(_detailImageView)
        .rightSpaceToView(_detailImageView, SJLayoutFrame(5))
        .heightIs(SJLayoutFrame(40))
        .widthIs(SJLayoutFrame(40));
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(9), SJLayoutFrame(13), SJLayoutFrame(9), SJLayoutFrame(50)));
        
    }
    return _detailImageView;
}

- (void)functionBar:(SJFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 编辑
            
        }
        
        if (index == 1) { // 移入收藏
            [weakSelf moveToFavorite];
        }
        
        if (index == 2) { // 副本收藏
            [weakSelf cpToFavorite];
        }
        
    }];
}

- (void)otherFunctionBar:(SJOtherFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 副本收藏
            if ([weakSelf.selectedItem.can_fav isEqualToString:@"1"]) {
                
                [SVProgressHUD showInfoWithStatus:@"内容受作者保护"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                return;
            }
            
            [weakSelf cpToFavorite];
        }
        
    }];
}


- (void)cpToFavorite {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = self.selectedItem.ID;
    parameters[@"source"] = @"6";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)moveToFavorite {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = self.selectedItem.ID;
    parameters[@"source"] = @"3";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}


- (void)moreAction {
    
    if ([self.selectedItem.is_me isEqualToString:@"1"]) { // 自己
        
        SJFunctionBar *functionBar = [[SJFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
        functionBar.delegate = self;
        
        [LEEAlert actionsheet].config
        .LeeAddCustomView(^(LEECustomView *custom) {
            custom.view = functionBar;
        })
        .LeeCornerRadius(SJCornerRadius)
        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            return SJScreenW - SJLayoutFrame(14);
        })
        .LeeHeaderInsets(UIEdgeInsetsZero)
        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
        .LeeShow();
        
    } else {
        
        SJOtherFunctionBar *functionBar = [[SJOtherFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
        functionBar.delegate = self;
        
        [LEEAlert actionsheet].config
        .LeeAddCustomView(^(LEECustomView *custom) {
            custom.view = functionBar;
        })
        .LeeCornerRadius(SJCornerRadius)
        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            return SJScreenW - SJLayoutFrame(14);
        })
        .LeeHeaderInsets(UIEdgeInsetsZero)
        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
        .LeeShow();
    }
    
}


- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(57), 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    
    return _collectionView;
}


#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return 80;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.item = item;
    
    if (cell.hidden) {
        cell.hidden = NO;
    }
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"音频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Audio" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"视频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Video" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
        
        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
        txtVC.item = item;
        [self.navigationController pushViewController:txtVC animated:YES];
    }
    
    
//    if ([item.fmt isEqualToString:@"1"]) {
//
//        self.selectedItem = item;
//        [self tapText:(SJOneCell *)cell item:item];
//    } else {
//
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//        treeVC.pageType = @"search";
//        [self.navigationController pushViewController:treeVC animated:YES];
//
//    }
    
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    
    SJTreeViewController *treeVC = [SJTreeViewController new];
    treeVC.item = item;
    treeVC.pageType = @"search";
    [self.navigationController pushViewController:treeVC animated:YES];
    
    
//    self.selectedItem = item;
//    
//    if ([item.fmt isEqualToString:@"1"]) { // 文字
//        
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//        treeVC.pageType = @"search";
//        [self.navigationController pushViewController:treeVC animated:YES];
//        
//    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
//        
//        [self tapPic:(SJOneCell *)cell item:item];
//        
//    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
//        
//        [self tapAudio:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"音频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Audio" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
//        
//        [self tapVideo:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"视频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Video" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
//        
//        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
//        txtVC.item = item;
//        [self.navigationController pushViewController:txtVC animated:YES];
//    }
    
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"icn_audio"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    
    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
    // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}


- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(45))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
    
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    if (self.searchField.text.length == 0) {
        
        NSString *msg = @"请输入关键词";
        [SVProgressHUD showErrorWithStatus:msg];
        WeakSelf;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [weakSelf.collectionView.mj_header endRefreshing];
        });
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    parameters[@"key"] = self.searchField.text;
    
    SJSearchApi *api = [[SJSearchApi alloc] initWithParameters:parameters];
   
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
            [self async];
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
            [self async];
        } else {
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            [self.collectionView.mj_header endRefreshing];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    if (self.searchField.text.length == 0) {
        
        NSString *msg = @"请输入关键词";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    parameters[@"key"] = self.searchField.text;
    
    SJSearchApi *api = [[SJSearchApi alloc] initWithParameters:parameters];
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
            [self async];
            
        } else {
            self.page--;
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}

- (void)async {
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        
        [self getItemOrigin];
        
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^{
            
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
            [self.collectionView.mj_header endRefreshing];
            
        });
    });
    
}


- (void)getItemOrigin {
    
    // 初始化二维数组
    NSMutableArray *grid = [NSMutableArray array];
    int max_t = (int)self.dataArray.count * SJItemCount;
    int max_w = SJItemCount;
    for (int i = 0; i < max_t; i++) {
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [grid addObject:arrl];
        for (int j = 0; j < max_w; j++) {
            grid[i][j] = @0;
        }
    }
    
    // 为每个 item 设置 l、t。
    for (SJWordItem *item in self.dataArray) {
        
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        NSMutableDictionary *dict = [self calLTWithW:w h:h grid:grid];
        
        if (dict != nil) {
            item.l = dict[@"l"];
            item.t = dict[@"t"];
        }
    }
}

- (NSMutableDictionary *)calLTWithW:(int)w h:(int)h grid:(NSMutableArray *)grid {
    
    int max_t = (int)grid.count;
    int max_w = SJItemCount;
    
    for (int i = 0; i < max_t; i++) {
        for (int j = 0; j < max_w; j++) {
            
            BOOL find = NO;
            if ([grid[i][j] isEqualToNumber:@0] && j + w <= max_w) {
                for (int m = 0; m < h; m++) {
                    for (int n = 0; n < w; n++) {
                        if ([grid[i + m][j + n] isEqualToNumber:@1]) {
                            find = YES;
                            break;
                        }
                    }
                    if (find) {
                        break;
                    }
                }
                
                if (!find) {
                    
                    NSMutableDictionary *dict =  [NSMutableDictionary dictionary];
                    dict[@"t"] = @(i);
                    dict[@"l"] = @(j);
                    
                    for (int m = 0; m < h; m++) {
                        for (int n = 0; n < w; n++) {
                            grid[i + m][j + n] = @1;
                        }
                    }
                    
                    return dict;
                }
            }
        }
    }
    return nil;
}



@end
